<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item>资产管理</a-breadcrumb-item>
        <a-breadcrumb-item>资产盘点计划</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <div class="filter">
        <a-form>
          <a-row>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="总计划名称" v-bind="formItemLayout" class="label-width-auto">
                <a-input v-model="name" placeholder="请输入" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="截止日期" v-bind="formItemLayout">
                <a-range-picker v-model="dateSection" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :lg="8" :xs="0">
              <a-button type="primary" @click="handleSearch()">查询</a-button>
              <a-button @click="reset">重置</a-button>
            </a-col>
          </a-row>
          <a-row>
            <a-col :lg="0" :md="24">
              <div class="btn-container">
                <a-button type="primary" @click="handleSearch()">查询</a-button>
                <a-button @click="reset">重置</a-button>
                <a-button type="primary" @click="handleAdd()"><a-icon type="plus" />新增总计划</a-button>
              </div>
            </a-col>
            <a-col :lg="8" :xs="0">
              <div class="btn-container">
                <a-button type="primary" @click="handleAdd()"><a-icon type="plus" />新增总计划</a-button>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div>
        <s-table
          ref="table"
          class="s-table"
          bordered
          row-key="id"
          :locale="{ emptyText: '无符合筛选条件的筛选项，请重新筛选！' }"
          :show-pagination="false"
          :columns="columns"
          :data="loadData"
          :alert="false"
        >
          <template slot="completeness" slot-scope="item">
            <a-progress :percent="item.completeness * 100" size="small" />
          </template>
          <template slot="action" slot-scope="item">
            <div class="action-container">
              <span class="success-link" @click="showDetail(item)">详情</span>
              <span>
                <a-dropdown>
                  <a-menu slot="overlay">
                    <a-menu-item @click="handleAdd(item)">新增子计划</a-menu-item>
                    <a-menu-item class="danger-link" @click="handleDel(item)">删除</a-menu-item>
                  </a-menu>
                  <span class="primary-link">选择操作</span>
                </a-dropdown>
              </span>
            </div>
          </template>
        </s-table>
        <!-- 分页器 -->
        <div class="pagination-container">
          <a-pagination
            :page-size="queryParam.pageSize"
            :show-total="total => `共 ${total} 条记录 第 ${queryParam.pageNum} / ${Math.ceil(total / queryParam.pageSize)} 页`"
            :current="queryParam.pageNum"
            :total="count"
            hide-on-single-page
            show-quick-jumper
            @change="handlePage"
          />
        </div>
      </div>

      <a-modal v-model="addPlanModal" title="新建计划">
        <a-form :form="form">
          <a-form-item label="总计划名称" required v-bind="formItemLayout" class="label-width-auto">
            <a-input
              v-decorator="[
                'name',
                { rules: [{ required: true, message: '请输入', whitespace: true }] },
              ]"
              placeholder="请输入"
            />
          </a-form-item>
        </a-form>
        <template slot="footer">
          <a-button @click="addPlanModal = false">取消</a-button>
          <a-button :loading="sending" class="primary-btn" @click="handleOk">确定</a-button>
        </template>
      </a-modal>

    </a-card>
  </page-view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { PageView, STable } from '@/components'

export default {
  name: 'Plan',
  components: { PageView, STable },
  inject: ['formItemLayout'],

  data () {
    return {
      sending: false,
      addPlanModal: false,
      form: this.$form.createForm(this),

      dateSection: [],
      name: undefined,
      count: 4,

      columns: [
        { title: '序号', align: 'center', dataIndex: 'id', width: '10%', customCell: this.customCell },
        { title: '总计划名称', align: 'center', dataIndex: 'name' },
        { title: '子计划数量', align: 'center', width: '15%', dataIndex: 'childCount' },
        { title: '截止日期', align: 'center', width: '15%', dataIndex: 'deadlineDate' },
        { title: '完成度', align: 'center', width: '20%', scopedSlots: { customRender: 'completeness' }},
        { title: '操作', align: 'center', width: '120px', scopedSlots: { customRender: 'action' }}
      ]
    }
  },

  computed: {
    ...mapState({
      queryParam: state => state.property.planQueryParam
    })
  },

  watch: {
    addPlanModal (bool) { if (!bool) this.form.resetFields() },

    queryParam: {
      handler ({ deadlineStart, deadlineEnd, name }) {
        const { dateSection, $moment } = this
        this.name = name || undefined
        dateSection.splice(0)
        if (deadlineStart && deadlineEnd) dateSection.push($moment(deadlineStart), $moment(deadlineEnd))
      },
      immediate: true,
      deep: true
    }
  },

  methods: {
    ...mapActions('property', ['setQueryParam']),

    refresh () {
      const table = this.$refs.table
      table && table.refresh && table.refresh()
    },

    handleParams () {
      const { queryParam } = this
      const res = {}
      for (const key in queryParam) {
        const item = queryParam[key]
        if (item) res[key] = item
      }
      return res
    },

    loadData () {
      const { handleParams, $axios, $get, $moment } = this
      const params = handleParams()
      const loadRes = { data: [] }

      return $axios.post('api/assetsInventoryPlan/query', params).then(res => {
        loadRes.data = $get(res, 'data.data.dataList', []).map(i => {
          const deadlineDate = i.deadline ? $moment(i.deadline).format('YYYY.MM.DD') : '-'
          return Object.assign(i, { deadlineDate })
        })
        return loadRes
      }).catch(e => loadRes)
    },

    customCell (record = {}) {
      const { endDate = '' } = record
      Object.assign(record, { endDate: endDate && endDate !== '-' ? this.$moment(endDate).format('YYYY.MM.DD') : '-' })
    },

    handleOk () {
      const { addPlan, form } = this
      form.validateFields((err, values) => {
        if (!err) {
          addPlan(values)
        }
      })
    },

    async addPlan (values) {
      if (this.sending) return false
      const { $axios, $get, $message } = this

      const { name } = values
      this.$toggleSending(1)
      const res = await $axios.post('api/assetsInventoryPlan/', { name, status: 1, pid: 0 }).then(res => res).catch(e => [])
      $message.destroy()
      if ($get(res, 'data.code') !== '000000') {
        $message.error($get(res, 'data.mesg', '请稍后再试'))
        return false
      }
      $message.info('新增成功')
      this.refresh()
      this.$toggleSending()
      this.addPlanModal = false
    },

    reset () {
      // this.setQueryParam({ target: this.queryParam, value: { name: undefined, deadlineStart: undefined, deadlineEnd: undefined }})
      this.dateSection.splice(0)
      this.name = undefined
    },

    handleDel ({ id = -1 }) {
      if (this.sending || id === -1) return false
      const { delPlan } = this
      this.$confirm({
        centered: true,
        maskClosable: true,
        title: '提示',
        content: '确定删除？',
        onOk () {
          delPlan(id)
        }
      })
    },

    async delPlan (id = -1) {
      const { $axios, $get, $message } = this
      this.$toggleSending(1)
      const res = await $axios.delete(`api/assetsInventoryPlan/${id}`).then(res => res).catch(e => [])
      $message.destroy()
      this.$toggleSending()
      if ($get(res, 'data.code') !== '000000') return $message.error($get(res, 'data.mesg', '请稍后再试'))
      $message.info('删除成功')
      this.refresh()
    },

    showDetail ({ name, id = -1 }) {
      if (id === -1 || !name) return false
      this.$router.push(`/property/plan/child/${name}/${id}`)
    },

    handleAdd (item = null) {
      if (!item) { // 总计划
        this.addPlanModal = true
      } else { // 子计划
        if (process.client) {
          const tempData = JSON.parse(sessionStorage.getItem('temp_new_plan_child') || '{}')
          delete tempData[`${item.name}${item.id}`]
          sessionStorage.setItem('temp_new_plan_child', JSON.stringify(tempData))
        }
        this.$router.push(`/property/plan/child/add/${item.name}/${item.id}`)
      }
    },

    handleSearch () {
      const { dateSection, name } = this
      const value = { name, deadlineStart: undefined, deadlineEnd: undefined }
      if (dateSection && dateSection.length > 1) {
        value.deadlineStart = dateSection[0].format('YYYY-MM-DD')
        value.deadlineEnd = dateSection[1].format('YYYY-MM-DD')
      }
      this.setQueryParam({ target: this.queryParam, value })
      // this.name = this.queryParam.name
      this.$handlePage()
    },

    handlePage (pageNum) {
      const { queryParam, dateSection, $moment } = this
      const { name, deadlineStart, deadlineEnd } = queryParam
      this.name = name
      dateSection.splice(0)
      if (deadlineStart && deadlineEnd) dateSection.push($moment(deadlineStart), $moment(deadlineEnd))
      this.setQueryParam({ target: this.queryParam, value: { pageNum }})
      this.$handlePage(pageNum)
    }
  }
}
</script>

<style lang="less" scoped>
</style>
